package com.tanhua.server.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.server.api.SoundApi;
import com.tanhua.dubbo.server.pojo.Sound;
import com.tanhua.dubbo.server.pojo.Times;
import com.tanhua.server.vo.SoundVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
@Slf4j
public class SoundService {

    @Reference(version = "1.0.0")
    private SoundApi soundApi;

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 声音上传
     *
     * @param soundFile 声音文件
     * @return
     */
    public Boolean saveSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();

        Sound sound = new Sound();
        sound.setUserId(user.getId());
        /*查询times表，如果没有查到，就新插入数据。
        判断表里面的created是否和系统时间是同一天，不是同一天就更新次数，同一天就不操作
        */
        try {
            //表中没有该数据，就插入一条，多使用判断语句
            if (null == this.soundApi.queryTimesById(user.getId())) {
                this.soundApi.insertTimesById(user.getId());
            }

            /*if (null == this.soundApi.queryTimesById(user.getId())){
                this.soundApi.insertTimesById(user.getId());
            }不能用null去判断，要用专门的工具类去判断
            集合不能用null去判断*/


            //上传声音到FastDFS中
            StorePath storePath = this.storageClient.uploadFile(soundFile.getInputStream(),
                    soundFile.getSize(),
                    StrUtil.subAfter(soundFile.getOriginalFilename(), '.', true),
                    null);
            sound.setSoundUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());

            String soundId = this.soundApi.saveSound(sound);

            return StrUtil.isNotEmpty(soundId);
        } catch (IOException e) {
            log.error("上传声音出错~ soundId = " + user.getId() + ", file = " + soundFile.getOriginalFilename(), e);
        }

        return false;
    }

    /**
     * 需要查询userInfo,sound,times三张表
     *
     * @return
     */
    //复用UserInfoService中的查userInfo表的方法
    //既要考虑代码的可阅读性，也要考虑性能，用变量保存值，少调用方法。
    public SoundVo receiveSound() {
        User user = UserThreadLocal.get();
        SoundVo soundVo = new SoundVo();
        //表中没有该数据，就插入一条，多使用判断语句
        try {
            if (null == this.soundApi.queryTimesById(user.getId())) {
                this.soundApi.insertTimesById(user.getId());
            }
            Long created = this.soundApi.queryTimesById(user.getId()).getUpdated();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String today = sdf.format(new Date(System.currentTimeMillis()));
            String pastDay = sdf.format(new Date(created));

            //判断是否有必要去更新用户的使用次数
            //次数和时间是要同时跟新的
            if (!(today.equals(pastDay))) {
                //日期不一致，更新次数，updated
                Times times = new Times();
                times.setUserId(user.getId());
                times.setReceiveTimes(10);
                times.setUpdated(System.currentTimeMillis());
                this.soundApi.updateTimes(times);
            }

            int receiveTimes = this.soundApi.queryTimesById(user.getId()).getReceiveTimes();
            Sound sound = this.soundApi.receiveSound(user.getId());
            if (null == sound) {
                return null;
            }
            UserInfo userInfo = this.userInfoService.queryUserInfoByUserId(sound.getUserId());
            soundVo.setId(sound.getUserId());
            soundVo.setAvatar(userInfo.getLogo());
            soundVo.setNickname(userInfo.getNickName());
            soundVo.setGender(userInfo.getSex().getValue() == 1 ? "man" : "woman");
            soundVo.setAge(userInfo.getAge());
            soundVo.setSoundUrl(sound.getSoundUrl());
            Times times = new Times();
            times.setUserId(user.getId());
            if (receiveTimes > 0) {
                times.setReceiveTimes(receiveTimes - 1);
                this.soundApi.updateReceiveTimes(times);
            }
            soundVo.setRemainingTimes(this.soundApi.queryTimesById(user.getId()).getReceiveTimes());
            return soundVo;
        } catch (Exception e) {
            log.error("接收语音消息出错~ userId = " + UserThreadLocal.get().getId(), e);
        }
        return null;
    }
}
